package com.cuanbo.dualscreenteachzhu.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;

import com.cuanbo.dualscreenteachzhu.activity.MainActivity;
import com.cuanbo.dualscreenteachzhu.bean.AtyInfo;
import com.cuanbo.dualscreenteachzhu.bean.ConfigInfo;
import com.cuanbo.dualscreenteachzhu.service.BackgroundService;
import com.cuanbo.dualscreenteachzhu.utils.DateUtil;
import com.cuanbo.dualscreenteachzhu.utils.FileUtil;
import com.cuanbo.dualscreenteachzhu.utils.LogUncaughtExceptionHandler;
import com.cuanbo.dualscreenteachzhu.utils.LogUtil;
import com.cuanbo.dualscreenteachzhu.utils.SSLUtil;
import com.cuanbo.dualscreenteachzhu.utils.SharedPreferencesUtil;
import com.cuanbo.dualscreenteachzhu.utils.WebServer;
import com.yanzhenjie.andserver.Server;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.wch.uartlib.WCHUARTManager;
import cn.wch.uartlib.chip.type.ChipType2;

public class App extends Application {
    public static long sysTime=0;
    public static String captureFileName;
    public static String videoPath;
    public static String videoFileName;
    public static boolean serverIPNetState;
    private static Context mContext;
    private static App instance;
    public static List<AtyInfo> atyInfoLst;
    public static ConfigInfo configInfo;
    public static boolean running;
    public static String commentPath;
    public static String capturePath;
    public static Server webServer;

    @Override
    public void onCreate() {
        super.onCreate();
        //将未捕获的异常写入到日志中
        Thread.setDefaultUncaughtExceptionHandler(new LogUncaughtExceptionHandler());
        commentPath=getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/html/img/comment.jpg";
        capturePath=getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/capture/"+ DateUtil.fmtYMD()+"/";
        new File(capturePath).mkdirs();
        running=true;
        instance = this;
        mContext = this;
        atyInfoLst = new ArrayList<>();
        configInfo= (ConfigInfo) SharedPreferencesUtil.getBean(this,ConfigInfo.class);
        if(configInfo==null){
            configInfo=new ConfigInfo();
            configInfo.setPwd("1");
            configInfo.setClassId(""+new Date().getTime());
            configInfo.setMatrixPort(1001);
            SharedPreferencesUtil.saveBean(this, App.configInfo);
        }
        instance=this;
        atyInfoLst = new ArrayList<>();
        WebServer.init();
        //忽略https证书验证
        SSLUtil.handleSSLHandshake();
        LogUtil.init(this);
        WCHUARTManager.getInstance().init(this);
        //WCHUARTManager.setReadTimeout(0);
        //WCHUARTManager.addNewHardware(0x1a86,0x7523);
        WCHUARTManager.setDebug(true);
        //增加0x1a86:0x55D4 并且强制指定类型为CH9102X
//        WCHUARTManager.addNewHardwareAndChipType(0x1a86,0x55D3, ChipType2.CHIP_CH343GP);
        //解决重复插拔导致的不识别问题
        WCHUARTManager.addNewHardwareAndChipType(0x1a86,0x55D8, ChipType2.CHIP_CH9101H);
        WCHUARTManager.addNewHardwareAndChipType(0x1a86,0x55D4,ChipType2.CHIP_CH9102F);
        //检查是否需要清空下载文件夹中的文件
        FileUtil.checkClearDir(App.getInstance().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), 1024);
        //启动后台服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, BackgroundService.class));
        } else {
            startService(new Intent(this, BackgroundService.class));
        }
    }

    public static App getInstance() {
        return instance;
    }

    /**
     * 添加指定Activity
     */
    public static void addAty(AtyInfo atyInfo) {
        atyInfoLst.add(0, atyInfo);
    }

    /**
     * 移除指定Activity
     */
    public static void removeAty(AtyInfo atyInfo) {
        atyInfoLst.remove(atyInfo);
    }

    /**
     * 显示MainActivity
     */
    public static void showMainActivity() {
        List<AtyInfo> removeAty = new ArrayList<>();
        for (int i = 0; i < atyInfoLst.size(); i++) {
            AtyInfo atyInfo = atyInfoLst.get(i);
            if (!(atyInfo.getAty() instanceof MainActivity)) {
                removeAty.add(atyInfo);
            }
        }
        atyInfoLst.removeAll(removeAty);
        for (int i = 0; i < removeAty.size(); i++) {
            Activity activity = removeAty.get(i).getAty();
            activity.finish();
        }
    }

    /**
     * 显示指定的activity
     */
    public static void showActivity(Class<?> cls) {
        List<AtyInfo> removeAty = new ArrayList<>();
        for (int i = 0; i < atyInfoLst.size(); i++) {
            AtyInfo atyInfo = atyInfoLst.get(i);
            if (!(atyInfo.getAty().getClass().getSimpleName().equals(cls.getSimpleName()))) {
                removeAty.add(atyInfo);
            } else {
                break;
            }
        }
        atyInfoLst.removeAll(removeAty);
        for (int i = 0; i < removeAty.size(); i++) {
            Activity activity = removeAty.get(i).getAty();
            activity.finish();
        }
    }

    /**
     * 获取指定的activity,如果没有找到返回null
     */
    public static AtyInfo getActivity(Class<?> cls) {
        for (int i = 0; i < atyInfoLst.size(); i++) {
            AtyInfo atyInfo = atyInfoLst.get(i);
            if (atyInfo.getAty().getClass().getSimpleName().equals(cls.getSimpleName())) {
                return atyInfo;
            }
        }
        return null;
    }

    /**
     * 获取正在显示的Activity对象
     */
    public static AtyInfo getShowingActivity() {
        for (int i = 0; i < atyInfoLst.size(); i++) {
            AtyInfo atyInfo = atyInfoLst.get(i);
            if (atyInfo.getState() == AtyInfo.STATE_RESUME) {
                return atyInfo;
            }
        }
        return null;
    }

    /**
     * 关闭所有Activity
     */
    public void closeAllAty() {
        for (int i = 0; i < atyInfoLst.size(); i++) {
            Activity activity = atyInfoLst.get(i).getAty();
            activity.finish();
        }
        atyInfoLst.removeAll(atyInfoLst);
    }

    /**
     * 退出App
     */
    public void exitApp() {
        running=false;
        closeAllAty();
    }

    public void restartApp() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent intent = new Intent(mContext, MainActivity.class);
            @SuppressLint("WrongConstant")
            PendingIntent restartIntent= PendingIntent.getActivity(mContext.getApplicationContext(), PendingIntent.FLAG_IMMUTABLE, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
            /*if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){

            }else{
                restartIntent= PendingIntent.getActivity(mContext.getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
            }*/
            //退出程序
            AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent); // 100ms后重启应用
            //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

}
